#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from celery import shared_task
from django.utils import timezone
import datetime

from book_app.models import BookBorrowRecordModel


@shared_task
def loan_period_reminder():
    now = timezone.now()
    borrow_obj = BookBorrowRecordModel.objects.filter(return_date__lt=now + datetime.timedelta(days=7),
                                                      return_date__gt=now, is_return=False)
    if not borrow_obj:
        print("无借阅超时记录")
        return False
    for record in borrow_obj:
        try:
            days = int((record.return_date - now).days)
            if days > 0:
                print("借阅人:{},你的书籍:《{}》,借阅期限快到期了,还剩余{}天".format(record.borrower, record.book.title, days))
            else:
                print("借阅人:{},你的书籍:《{}》,借阅期限已过期了,超出{}天".format(record.borrower, record.book.title,
                                                               abs(days)))
        except Exception as e:
            print("loan_period_reminder error is {}".format(e))
    return True
